/*
 * ConnectionInfo.java
 *
 * Research In Motion Limited proprietary and confidential
 * Copyright Research In Motion Limited, 2011-2011
 */
package com.allkapps.bbmopenchat;

import net.rim.blackberry.api.bbm.platform.io.BBMPlatformChannel;
import net.rim.blackberry.api.bbm.platform.io.BBMPlatformConnection;
import net.rim.blackberry.api.bbm.platform.io.BBMPlatformSession;

import com.allkapps.bbmopenchat.utils.BBMUtils;

/**
 * A convenience class for containing the connection and providing methods
 * for cleanup and rendering. This class can be used in an object list field
 * for display since it implements {@link #toString()}.
 *
 */
public class ConnectionInfo {

    private final BBMPlatformConnection _connection;
    
    public ConnectionInfo(BBMPlatformConnection connection) {
        _connection = connection;
    }
    
    public BBMPlatformConnection getConnection() {
        return _connection;
    }
    
    public void cleanup(boolean destroy) {
        if (_connection instanceof BBMPlatformChannel) {
            BBMPlatformChannel channel = (BBMPlatformChannel) _connection;
            if (channel != null) {
                try {
                    channel.destroy();
                } catch (IllegalStateException e) {
                    // channel already destroyed: ignore
                }
            }
            
        } else if (_connection instanceof BBMPlatformSession) {
            BBMPlatformSession session = (BBMPlatformSession) _connection;
            if (session != null) {
                try {
                	if(destroy){
                		session.end();
                	} else {
                		session.leave();
                	}
                } catch (IllegalStateException e) {
                    // session already closed: ignore
                }
            }
        }
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return BBMUtils.getConnectionName( _connection );
    }
    
    
}
